package com.sh.data.engine.repository.config;

import com.aliyun.gts.sso.context.SFLoginAccountContext;
import com.aliyun.gts.sso.domain.LoginInfo;
import com.aliyun.gts.sso.domain.User4ADTO;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Date;

/**
 * 数据源配置
 *
 * @author: mengzheng.mhc
 * @date: 2024/5/29 11:54
 */
@Configuration
@MapperScan(
    basePackages = "com.sh.data.engine.repository.dao",
    sqlSessionFactoryRef = "engineSqlSessionFactory")
public class MybatisPlusConfig {

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            private static final String createTimeField = "createTime";
            private static final String updateTimeField = "updateTime";
            private static final String creatorIdField = "creatorId";
            private static final String updaterIdField = "updaterId";

            @Override
            public void insertFill(MetaObject metaObject) {
                Object createTime = this.getFieldValByName(createTimeField, metaObject);
                if (null == createTime) {
                    this.setFieldValByName(createTimeField, new Date(), metaObject);
                }

                Object updateTime = this.getFieldValByName(updateTimeField, metaObject);
                if (null == updateTime) {
                    this.setFieldValByName(updateTimeField, new Date(), metaObject);
                }

                Object creatorId = this.getFieldValByName(creatorIdField, metaObject);
                if (null == creatorId) {
                    this.strictInsertFill(metaObject, creatorIdField, String.class, getCurrentUserId());
                }

                Object updaterId = this.getFieldValByName(updaterIdField, metaObject);
                if (null == updaterId) {
                    this.setFieldValByName(updaterIdField, getCurrentUserId(), metaObject);
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName(updateTimeField, new Date(), metaObject);
                this.setFieldValByName(updaterIdField, getCurrentUserId(), metaObject);
            }
        };
    }

//    private String getCurrentUserId() {
//        LoginInfo loginInfo = SFLoginAccountContext.getLoginInfo();
//        if (loginInfo == null) {
//            return null;
//        }
//        LoginAccount loginAccount = loginInfo.getLoginAccount();
//        if (loginAccount == null) {
//            return null;
//        }
//        return loginAccount.getGuid();
//    }

    private String getCurrentUserId() {
        Integer status = SFLoginAccountContext.getStatus();
        if (status == null) {
            return null;
        }
        if (status == 200) {
            LoginInfo loginInfo = (LoginInfo) SFLoginAccountContext.getLoginInfo();
            if (loginInfo == null) {
                return null;
            }
            return loginInfo.getLoginAccount().getGuid();
        } else if (status == 201) {
            User4ADTO user = (User4ADTO) SFLoginAccountContext.getLoginInfo();
            if (user == null) {
                return null;
            }
            return user.getId();
        }
        return null;
    }

//    @Bean
//    public DatabaseIdProvider databaseIdProvider() {
//        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
//        Properties properties = new Properties();
//        properties.put("Oracle", "oracle"); // 支持oracle和达梦
//        properties.put("MySQL", "mysql");
//        properties.put("PostgreSQL", "pg");
//        databaseIdProvider.setProperties(properties);
//        return databaseIdProvider;
//    }

    @Bean(name = "engineDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.engine")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("engineSqlSessionFactory")
    public SqlSessionFactory engineSqlSessionFactory(@Qualifier("engineDataSource") DataSource dataSource)
        throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**/*.xml"));
        sqlSessionFactory.setPlugins(mybatisPlusInterceptor());
//        sqlSessionFactory.setDatabaseIdProvider(databaseIdProvider());
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(metaObjectHandler());
        globalConfig.setBanner(true);
        sqlSessionFactory.setGlobalConfig(globalConfig);
        return sqlSessionFactory.getObject();
    }

    @Bean(name = "engineTransactionManager")
    @Primary
    public PlatformTransactionManager engineTransactionManager(
        @Qualifier("engineDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "engineSqlSessionTemplate")
    public SqlSessionTemplate engineSqlSessionTemplate(
        @Qualifier("engineSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
